<template>
  <view>
    <form>
      

      <!-- <view class="cu-card margin radius">
        <view class="cu-form-group margin-top">
        <view class="title">工程编号</view>
        <view>{{ dataInfo.projectno }}</view>
      </view>
      <view class="cu-form-group">
        <view class="title xm-title">工程名称</view>
        <view class="sub-title">{{ dataInfo.projectname }}</view>
      </view>
      </view> -->
      <xmInfo
      :projectno="dataInfo.projectno"
      :projectname="dataInfo.projectname"
    ></xmInfo>
      <view class="cu-form-group">
        <view class="title"><text class="cuIcon-favorfill text-xs text-red"></text>结果</view>
        <!-- <switch @change="SwitchA" :class="switchA?'checked':''" :checked="switchA?true:false"></switch> -->
        <!-- <switch :checked="dataInfo.state == 0?true:false"  @change="switch1Change" /> -->
        <js-radio v-model="dataInfo.state" dict-type="zf_material_check_status"></js-radio>
      </view>
      <view class="cu-form-group">
        <view class="title"><text class="cuIcon-favorfill text-xs text-red"></text>抽检日期</view>
        <picker
          mode="date"
          :value="dataInfo.checkdate ? dataInfo.checkdate :date"
          @change="DateChange"
        >
          <view class="picker">
            {{ dataInfo.checkdate ? dataInfo.checkdate : '请选择抽检日期' }}
          </view>
        </picker>
      </view>
      <view class="cu-form-group" style="min-height: 0"></view>
      <view class="cu-bar bg-white cu-bar1">
        <view class="action"><text class="cuIcon-kb text-xs text-red"></text>备注</view>
      </view>

      <view class="cu-form-group">
        <textarea
          maxlength="-1"
          :disabled="modalName != null"
          :value="dataInfo.remark"
          @input="textareaAInput"
          placeholder="备注"
        ></textarea>
      </view>

      <view class="cu-form-group" style="min-height: 0"></view>
      <view class="cu-bar bg-white cu-bar1">
        <view class="action"><text class="cuIcon-kb text-xs text-red"></text>图片上传</view>
      </view>
      <view class="cu-form-group">
        <js-uploadfile
          v-model="dataInfo.dataMap"
          :biz-key="dataInfo.id"
          biz-type="pmMaterialcheck_image"
        ></js-uploadfile>
      </view>

      <!-- <file-upload
        :uploadOptions="uploadOptions"
        :imgList="dataInfo.dImageList"
        @imgListChange="imgListChange"
      ></file-upload> -->
      <!-- <view>
        <movable-area class="movable-area">
          <movable-view class="movable-view" :x="x" :y="y" direction="all">
            <view class="cu-bar bg-white flex-end" @click="addDetail">
        <view class="action"
          >材料明细<text class="cuIcon-roundadd padding text-red text-xsl"></text
        ></view>
      </view>
          </movable-view>
        </movable-area>
      </view> -->




      <view class="cu-card"  v-if="dataInfo.pmMaterialchecksList && dataInfo.pmMaterialchecksList.length">
        <view
          class="cu-item shadow"
          v-for="(item, index) in dataInfo.pmMaterialchecksList"
          :key="index"
          v-if="item && item.status != 1"
        >
          <view class="cu-form-group">
            <view class="text-xl text-bold">
              <view
                  style="
                    display: inline-block;
                    padding: 5px;
                    background: #3e97b0;
                    color: #fff;
                    width: 40px;
                    text-align: center;
                    font-style: italic;
                    font-weight: bold;
                  "
                  class="margin-right-sm"
                >
                  {{ index + 1 }}
                </view>
                {{ item.mname ? item.mname : item.metername }}</view>
            <view class="text-xl text-bold"></view>
          </view>
          <view class="cu-form-group padding">
            <view class="title">材料编码</view>
            <view>{{ item.mcode  ? item.mcode : item.metercode }}</view>
          </view>
          <view class="cu-form-group">
            <view class="title">规格型号</view>
            <view>{{ item.mstd }}</view>
          </view>
          <view class="cu-form-group">
            <view class="title"><text class="cuIcon-kb text-xs text-red"></text>备注</view>
            <view><input placeholder="请输入备注" name="input" v-model="item.remarks" class="input-align"/></view>
          </view>
          <view class="cu-form-group" style="min-height: 0"></view>
          <view class="cu-bar bg-white cu-bar1">
            <view class="action"><text class="cuIcon-kb text-xs text-red"></text>材料图片</view>
          </view>
          <js-uploadfile
              v-model="item.dataMap"
              :biz-key="item.id"
              biz-type="pmMaterialcheck_image_child"
            ></js-uploadfile>

          <view class="cu-bar bg-white">
            <view class="action"></view>
            <view>
              <text class="cuIcon-deletefill padding text-sl text-red" @click="DelItem(item.pmid?item.pmid:item.id)" ></text>
            </view>
          </view>
        </view>
      </view>
      <view style="height: 180rpx"></view>
      <view class="btn-group cu-bar foot">
        
        <button class="cu-btn line-green shadow-blur" @click="addDetail">材料明细<text class="cuIcon-roundadd padding text-red text-xsl"></text
        ></button> 
        <!--v-if="!!dataInfo.id&&addflag"-->
        <view class="flex">
            <js-bpm-button
          v-model="dataInfo.bpm"
          :biz-key="dataInfo.id"
          form-key="material_check"
          @complete="submit"
          :showTraceText="showTraceText"
        ></js-bpm-button>
        </view>
        <!--
          <view class="flex" v-else-if="!dataInfo.id">
            <js-bpm-button
          v-model="dataInfo.bpm"
          :biz-key="dataInfo.id"
          form-key="material_check"
          @complete="submit"
        ></js-bpm-button>
        </view>  
        -->
        
      </view>
    </form>
    <add-detail
      :modalNameDetail="modalNameDetail"
      @modalNameDetailEmit="modalNameDetailEmit"
      @checkedListEmit="checkedListEmit"
      v-if="showAddDetail"
    ></add-detail>
  </view>
</template>
<script>
import addDetail from "./addDetail.vue";
import xmInfo from "@/pages/zfgs/index/componetns/xmInfo.vue";
import {hasPermission} from '@/common/fire.js'
export default {
  components: {
    addDetail,
    xmInfo
  },
  data() {
    return {
      uploadOptions: {},
      switchA: false,
      date: new Date().toISOString().substring(0, 10),
      modalName: null,
      modalNameDetail: null,
      showAddDetail: false,
      dataInfo: {
        id: "",
        bpm: {},
        pmMaterialchecksList: [],   
      },
      isSubmitting: false,
      showButton: true,
      x: 650, //x坐标
      y: 650, //y坐标
      addflag: hasPermission('btn:add:cailiaochoujian'),
      editflag: hasPermission('material:check:pmMaterialcheck:edit'),
      bpmTaskId: '',
      showTraceText: true,
    };
  },
  onLoad(e) {
    if (!!e.id) {
      this.showButton = true;
      this.getCheckPmMaterialcheckForm(e.id);
      this.dataInfo.id = e.id
      this.bpmTaskId = e['bpm.taskId'];
      if (!this.bpmTaskId) {
        this.showTraceText = false;
        
      }
    }
    if (!!e.xm) {
      this.showButton = true;
      this.dataInfo = JSON.parse(e.xm);
      //   巡检人
    }
  },
  methods: {

    submit() {
      if(!this.dataInfo.state){
        this.$u.toast("抽检结果必选");
        return;
      }      
      if(!this.dataInfo.checkdate){
        this.$u.toast("抽检日期必选");
        return;
      }
      if (this.isSubmitting) {
        return;
      } else {
        this.isSubmitting = true;
        try {
			this.dataInfo.status = 4;
          this.$u.api.zfgs
            .checkPmMaterialcheckSave(this.dataInfo)
            .then((res) => {
              if (res.result == "true") {
                this.$u.toast(res.message);
                const itemContent = {
                  projectno: this.dataInfo.projectno,
                  projectname: this.dataInfo.projectname,
                };
                setTimeout(() => {
                  // uni.navigateTo({
                  //   url:
                  //     "/pages/zfgs/material/check/pmMaterialcheck/list?item=" +
                  //     JSON.stringify(itemContent),
                  // });
				  uni.navigateBack({
				  	delta: 1,
				  });
                }, 500);
              }else{
                this.$u.toast(res.message);
              }
            });
        } catch (error) {
          this.$u.toast(error.message);
        } finally {
          this.isSubmitting = false;
        }
      }
    },

    DelItem(pmid) {
      uni.showModal({
        title: "",
        content: "确定要删除吗？",
        cancelText: "取消",
        confirmText: "确认",
        success: (res) => {
          if (res.confirm) {
            // 根据item.zhengGaiNo 查找要删除的项
            // let index = this.dataInfo.rectList.findIndex(
            //   (item) => item.id == items.id
            // );
            this.dataInfo.pmMaterialchecksList.map((item) => {
              console.log(item,'item===',pmid);
              if (item.pmid == pmid) {
                item.status = 1; //状态为1删除
                // 深度监听dataInfo.rectList
              }else if(item.id == pmid){
                item.status = 1;
              }

            });
            this.$forceUpdate();
            console.log(this.dataInfo.pmMaterialchecksList);
            this.$u.toast("删除成功");
          }
        },
      });
    },
    getCheckPmMaterialcheckForm(id) {
      this.$u.api.zfgs
        .checkPmMaterialcheckForm({
          id: id,
        })
        .then((res) => {
          console.log(res, "res===");
          this.dataInfo = res.pmMaterialcheck;
        });
    },
    SwitchA(e) {
      // this.switchA = e.detail.value
    },
    DateChange(e) {
      this.dataInfo.checkdate = e.detail.value;
      this.$forceUpdate();
    },
    textareaAInput(e) {
      console.log(e.detail.value,'textareaAInput');
      this.dataInfo.remark = e.detail.value;
    },
    addDetail() {
      this.showAddDetail = true;

      this.modalNameDetail = "DrawerModalR";

      console.log(this.modalNameDetail);
    },
    modalNameDetailEmit(e) {
      this.modalNameDetail = e;
    },
    async checkedListEmit(e) {
      console.log(e, "checkedListEmit", this.dataInfo);
      if (!this.dataInfo.pmMaterialchecksList) {
        this.dataInfo.pmMaterialchecksList = [];
      }

      // 将 e 中的每个项目转换为所需格式

      let eArray = [];
      e.forEach((item) => {
        eArray.push({
          pmid: item.id,
          metercode: item.mcode,
          metername: item.mname,
          mstd: item.mstd
        });
      });

      if (this.dataInfo.pmMaterialchecksList.length == 0) {
        this.dataInfo.pmMaterialchecksList = eArray;
      } else {

      // 创建一个新数组用于存放最终结果
        let newArray = [];

        // 遍历原始数据
        this.dataInfo.pmMaterialchecksList.forEach((originalItem) => {
          let matched = false; // 标记是否找到了匹配项

          // 遍历eArray
          eArray.forEach((updateItem) => {
            if (originalItem.pmid === updateItem.pmid) {
              // 找到匹配项，标记并保存更新后的项目
              matched = true;
              newArray.push(updateItem);
            }
          });

          // 如果没有在eArray中找到匹配项，则保留原始项目
          if (!matched) {
            newArray.push(originalItem);
          }
        });

        // 将eArray中未在原始列表中找到匹配pmid的项追加到newArray
        eArray.forEach((itemFromEArray) => {
          let exists = newArray.some((item) => item.pmid === itemFromEArray.pmid);
          if (!exists) {
            newArray.push(itemFromEArray);
          }
        });

        // 最后，将处理后的数组赋值回原对象
        this.dataInfo.pmMaterialchecksList = newArray;    

      }



    },

  },
};
</script>
<style lang="scss" scoped>
$all_width: 140rpx;
$all_height: 140rpx;
.movable-area {
  z-index: 999;
  height: 97vh;
  width: 650rpx;
  // max-width: 1152rpx;
  // 固定在右边
  top: -150rpx;
  position: fixed;
  right: $all_width;
  // 固定在右下角
  pointer-events: none; //此处要加，鼠标事件可以渗透
  .movable-view {
    width: $all_width;
    height: $all_height;
    pointer-events: auto; //恢复鼠标事件
    .cu-bar{
      width: 320rpx;
    }
  }
}
.action {
  color: #303133;
}
.cu-form-group {
  flex-wrap: wrap;
}
.text-sl {
  font-size: 22px !important;
}
.cu-bar {
  min-height: 80px;
}
.cu-bar1{
  min-height: 50px !important;
}
.cu-btn {
  font-size: 16px;
  height: 40px;
}
.foot {
  z-index: 997;
  background: #fff;
}
.green {
  color: green;
}
.input-align {
  text-align: right;
}
.sub-title{
  flex-grow: 1; /* 让右侧内容占据剩余空间 */
  max-width: 200px; /* 或其他合适的最大宽度，超过这个宽度时内容会换行 */
  word-break: break-word; /* 或 overflow-wrap: break-word; 允许单词在必要时断开以适应宽度 */
}
.xm-title{
  flex-basis: 100px; /* 或其他合适的固定宽度，用于左侧标题 */
  flex-shrink: 0; /* 防止标题在小屏幕下收缩 */
  overflow: hidden; /* 可选，防止内容溢出 */
}
.text-xsl {
  font-size: 60rpx !important;
}
.flex-end {
  display: flex;
  justify-content: flex-end;
}
.text-xs {
  font-size: 18rpx !important;
}
.cu-item{
  border: 1px solid #39b54a;
}
.cuIcon-kb::before {
    // content 为空白
    display: inline-block;
    content: ' ';
    width: 18rpx;
    height: 100%;
    
}
</style>